package com.contactbook.web.controller.group;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.contactbook.web.service.GroupClient;

import contactbook.model.Account;

public class IndexGroupController extends HttpServlet implements Servlet {

	private static final long serialVersionUID = 1L;
	
	private GroupClient groupClient;
	
	public IndexGroupController() {
		super();
    	groupClient = new GroupClient();
	}
	
	public void init() throws ServletException {
    	super.init();
    }
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		redirect(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		redirect(request, response);
	}
	
	private void redirect(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession(true);
		Account account = (Account)session.getAttribute("account");
		RequestDispatcher dispatcher = request.getRequestDispatcher("/Index");
	
		if (account != null) {	
			groupClient.login(account.getLogin(), account.getPassword());
			
			request.setAttribute("groups", groupClient.getGroups().iterator());
			request.setAttribute("nbGroups", groupClient.getGroups().size());
			dispatcher = request.getRequestDispatcher("/groups.jsp");
			
			groupClient.logout();
		}
		
		dispatcher.forward(request, response);
    }
	
	public void destroy() {
		super.destroy();
	}

}
